package com.westar.core.controller;

import com.westar.base.businessUtil.ImplementPageUtil;
import com.westar.base.cons.Constant;
import com.westar.base.emum.PublicServiceEnum;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.TokenUtil;
import com.westar.base.util.WestarHttpUtil;
import com.westar.core.conf.SysConst;
import com.westar.core.services.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

@RestController
@EnableAutoConfiguration
@RequestMapping("/admin")
@Api("系统管理级别的操作")
public class AdminOptController {

    private static Logger logger = LoggerFactory.getLogger(AdminOptController.class);

    @Autowired
    private AreaService areaService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AffairInfoService affairInfoService;

    @Autowired
    private Environment env;

    @ApiOperation("同步区域数据")
    @RequestMapping(value = "/initArea", method = RequestMethod.GET, produces = "application/json")
    public WestarResult initArea(){
        try {
            UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);
            String token = TokenUtil.initToken( adminUser.getAccount(),adminUser.getPasswd(), Constant.MODEL_OAUTHUI);

            String actCookie = TokenUtil.getCookie(token, Constant.MODEL_OAUTHUI);
            return areaService.initArea(actCookie);
        } catch (IOException e) {
            e.printStackTrace();
            return WestarResult.build( -1,"请求错误！" );
        } catch (SelfHttpException e) {
            e.printStackTrace();
            return WestarResult.build( -1,"登录错误！" );
        }
    }

//    @ApiOperation("同步部门数据")
//    @RequestMapping(value = "/initDep", method = RequestMethod.GET, produces = "application/json")
//    public WestarResult initDep() {
//        try {
//            String account = PublicConfig.SYSCONF.get("admin_account");
//            UserInfo adminUser = userInfoService.getUserInfoByAccount(account);
//            String token = WestarHttpUtil.getSupAdminToken(adminUser);
//
//            String actCookie = WestarHttpUtil.getCookie(token);
//            departmentService.initDepartment( actCookie );
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (SelfHttpException e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }

    /**
     * 初始化用户信息
     * @return
     */
    @ApiOperation("同步用户数据")
    @RequestMapping(value = "/initUser", method = RequestMethod.GET, produces = "application/json")
    public WestarResult initUser(){
        try {
            UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);
            String token = TokenUtil.initToken( adminUser.getAccount(),adminUser.getPasswd(), Constant.MODEL_OAUTHUI);
            String actCookie = TokenUtil.getCookie(token, Constant.MODEL_OAUTHUI);
            userInfoService.initUser(actCookie);
            return new WestarResult(0,"success","同步成功");
        } catch (IOException e) {
            logger.error("同步用户数据,一体化管理员账号不能正常使用");
            return new WestarResult(-1,"error","一体化管理员账号不能正常使用"  );
        } catch (SelfHttpException e) {
            if(e.getCode().equals(SelfHttpException.PAGE_RE_LOGIN  ) ){
                return initUser();
            }else{
                logger.error("同步用户数据出错！");
                return new WestarResult(-1,"error",e.getMsg() );
            }
        }
    }

    /**
     * 初始化实施清单，分区域的
     * @return
     */
    @ApiOperation("初始化实施清单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="eventName",dataType="String",required=true,value="事项编号"),
            @ApiImplicitParam(paramType="query",name="areaCode",dataType="String",required=false,value="区域编码"),
            @ApiImplicitParam(paramType="query",name="isNotPublicServices",dataType="String",required=false,value="事项类型")
    })
    @RequestMapping(value = "/queryImplementDetail", method = RequestMethod.POST, produces = "application/json")
    public WestarResult queryImplementDetail(String eventName,String areaCode,String isNotPublicServices){
        //除开遂宁，其他项目需要传递照片
        if(StringUtils.isNotEmpty(SysConst.ITEM_NAME) && "suining".equals(SysConst.ITEM_NAME)){
            String[] areaCodes = new String[]{"510900000000","510903000000","510904000000"
                    ,"510921000000","510922000000","510923000000","510906000000","510907000000"};
            if(StringUtils.isNotEmpty(areaCode) && !Arrays.asList(areaCodes).contains(areaCode)){
                return WestarResult.build( -1,"区域编码错误！仅支持【遂宁市】510900000000，【船山区】510903000000，" +
                        "【安居区】510904000000，【蓬溪县】510921000000，【射洪县】510922000000，【大英县】510923000000，" +
                        "【遂宁经济技术开发区】510906000000，【遂宁市河东新区管理委员会】510907000000" );
            }
        }else{
            //默认区划名称
            String defAreaCode = env.getProperty("dataexchange.toparea.areaCode");
            areaCode = defAreaCode;
        }

        if(StringUtils.isNotEmpty(isNotPublicServices)
                && null == PublicServiceEnum.getEnum(isNotPublicServices)){
            return WestarResult.build( -1,"isNotPublicServices：参数为power 、 service 或 空" );
        }
        if(StringUtils.isEmpty(isNotPublicServices)){
            isNotPublicServices = PublicServiceEnum.POWER.getParam();
        }

        try {
            UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);

            String token = TokenUtil.initToken( adminUser.getAccount(),adminUser.getPasswd(),Constant.MODEL_THINGSUI);
            String actCookie = TokenUtil.getCookie(token,Constant.MODEL_THINGSUI);

            WestarResult westarResult = ImplementPageUtil.queryAllImplementDetailWithMaterial(actCookie,eventName,areaCode,isNotPublicServices) ;

            if(westarResult.getMsg().equals("未查询到结果！")){
                List<Map<String, String>> mapList = PublicServiceEnum.toList();
                //用当前账号取得实施事项详情信息【其他模块】
                for(Map<String, String> subMap : mapList){
                    String subisNotPublicServices = subMap.keySet().iterator().next();
                    if(subisNotPublicServices.equals(isNotPublicServices)){
                        continue;
                    }
                    westarResult = ImplementPageUtil.queryAllImplementDetailWithMaterial(actCookie,eventName,areaCode,subisNotPublicServices) ;
                    if(westarResult.getStatus()==0){
                        break;
                    }
                }
            }


            return westarResult;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SelfHttpException e) {
            e.printStackTrace();
        }
        return null;

    }

    @ApiOperation("获取样表附件信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="fileUrl",dataType="String",required=true,value="附件的url")
    })
    @RequestMapping(value = "/downLoadFileFromUp", method = RequestMethod.GET)
    public void downLoadFileFromUp(String fileUrl, HttpServletResponse httpServletResponse){
        UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);
        try {
            String token = TokenUtil.initToken( adminUser.getAccount(),adminUser.getPasswd(),Constant.MODEL_THINGSUI);
            String actCookie = TokenUtil.getCookie(token,Constant.MODEL_THINGSUI);

            //创建一个uri对象
            URIBuilder uriBuilder = new URIBuilder(fileUrl);
            List<NameValuePair> listNameValuePair = uriBuilder.getQueryParams();
            Map<String, String> searchParam = new HashMap<>();
            for (NameValuePair nameValuePair: listNameValuePair ) {
                searchParam.put(nameValuePair.getName(),nameValuePair.getValue());
            }
            String baseUrl = fileUrl.substring(0,fileUrl.indexOf("?"));

            WestarHttpUtil.getMethodForFile(baseUrl,actCookie,searchParam,httpServletResponse);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SelfHttpException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    /**
     * 需要解密的用户
     * @return
     */
    @ApiOperation("需要解密的用户")
    @RequestMapping(value = "/listUserForPasswd", method = RequestMethod.GET, produces = "application/json")
    public WestarResult listUserForPasswd(){
        List<UserInfo> userInfoList = userInfoService.listUserForPasswd();
        return WestarResult.ok(userInfoList);
    }


//    /**
//     * 初始化实施清单，不区分区域的
//     * @return
//     */
//    @ApiOperation("初始化实施清单，不区分区域的")
//    @RequestMapping(value = "/initImplement", method = RequestMethod.GET, produces = "application/json")
//    public WestarResult initImplement(){
//        try {
//            String account = PublicConfig.SYSCONF.get("admin_account");
//            UserInfo adminUser = userInfoService.getUserInfoByAccount(account);
//            String token = WestarHttpUtil.getSupAdminToken(adminUser);
//            String actCookie = WestarHttpUtil.getCookie(token);
//            implementService.initImplement(actCookie);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (SelfHttpException e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }

//    /**
//     * 初始化是事情的那详情信息，按区域的
//     * @return
//     */
//    @ApiOperation("初始化是事情的那详情信息，按区域的")
//    @RequestMapping(value = "/initImplementDetail", method = RequestMethod.GET, produces = "application/json")
//    public WestarResult initImplementDetail(){
//        try {
//            String account = PublicConfig.SYSCONF.get("admin_account");
//            UserInfo adminUser = userInfoService.getUserInfoByAccount(account);
//            String token = WestarHttpUtil.getSupAdminToken(adminUser);
//            implementService.initImplementDetail(token);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (SelfHttpException e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }
    @ApiOperation("分页查询上传一体化的办件")
    @RequestMapping(value = "/listPagedAffairInfo", method = RequestMethod.GET, produces = "application/json")
    public WestarResult listPagedAffairInfo(){
//        affairInfoService.listPagedAffairInfo();
        return WestarResult.ok();
    }
}
